//
//  NSMutableAttributedString+textKit.m
//  iosapp
//
//  Created by 王晨 on 15/10/14.
//  Copyright © 2015年 oschina. All rights reserved.
//

#import "NSMutableAttributedString+textKit.h"
#import "Utils.h"
#import "KILabel.h"
#import <objc/runtime.h>

#define EmojiRegex @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]|:[a-zA-Z0-9\\u4e00-\\u9fa5_]+:"
#define LinkRegex @"<a href=['\"]([^<'\"]+)[^<]+>([^<]+)</a>"

@implementation NSMutableAttributedString (textKit)

- (void)setLinkRanges:(NSArray *)linkRanges {
    objc_setAssociatedObject(self, @"linkRanges", linkRanges, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSArray*)linkRanges {
    return objc_getAssociatedObject(self, @"linkRanges");
}

+ (NSMutableAttributedString*)textWithEmoji:(NSString*)text withHasAttach:(BOOL)hasAttach {
    NSMutableAttributedString * result = [[NSMutableAttributedString alloc] init];
    [result setTextWithEmoji:text withHasAttach:hasAttach];
    return result;
}

- (void)setTextWithEmoji:(NSString*)text withHasAttach:(BOOL)hasAttach{
    NSRange range = NSMakeRange(0, self.length);
    [self replaceCharactersInRange:range withString:text];
    
    // 添加语音图片
    if (hasAttach) {
        [self insertAttach];
    }
    [self analyzeEmoji];
    [self analyzeLink];
}

- (void)insertAttach {
    NSTextAttachment *textAttachment = [NSTextAttachment new];
    textAttachment.image = [UIImage imageNamed:@"audioTweet"];
    NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment];
    
    [self insertAttributedString:[[NSAttributedString alloc] initWithString:@" "] atIndex:0];
    [self insertAttributedString:attachmentString atIndex:0];
}

- (void)analyzeEmoji
{
    NSDictionary *emoji = [Utils emojiDict];

    NSMutableString * string = [[NSMutableString alloc] initWithString:self.string];
    NSRegularExpression *re = [[NSRegularExpression alloc] initWithPattern:EmojiRegex
                                                                          options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators
                                                                            error:nil];
    NSArray *resultsArray = [re matchesInString:string
                                               options:NSMatchingReportCompletion
                                                 range:NSMakeRange(0, string.length)];
    
    NSMutableArray *emojiArray = [NSMutableArray arrayWithCapacity:resultsArray.count];
    
    for (NSTextCheckingResult *match in resultsArray) {
        NSRange range = [match range];
        NSString *emojiName = [string substringWithRange:range];
        
        if ([emojiName hasPrefix:@"["] && emoji[emojiName]) {
            NSTextAttachment *textAttachment = [NSTextAttachment new];
            textAttachment.image = [UIImage imageNamed:emoji[emojiName]];
            [textAttachment adjustY:-3];
            
            NSAttributedString *emojiAttributedString = [NSAttributedString attributedStringWithAttachment:textAttachment];
            
            [emojiArray addObject: @{@"image": emojiAttributedString, @"range": [NSValue valueWithRange:range]}];
        } else if ([emojiName hasPrefix:@":"]) {
            if (emoji[emojiName]) {
                [emojiArray addObject:@{@"text": emoji[emojiName], @"range": [NSValue valueWithRange:range]}];
            } else {
                UIImage *emojiImage = [UIImage imageNamed:[emojiName stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@":"]]];
                NSTextAttachment *textAttachment = [NSTextAttachment new];
                textAttachment.image = emojiImage;
                [textAttachment adjustY:-3];
                
                NSAttributedString *emojiAttributedString = [NSAttributedString attributedStringWithAttachment:textAttachment];
                
                [emojiArray addObject: @{@"image": emojiAttributedString, @"range": [NSValue valueWithRange:range]}];
            }
        }
    }
    
    for (NSInteger i = emojiArray.count -1; i >= 0; i--) {
        NSRange range;
        [emojiArray[i][@"range"] getValue:&range];
        if (emojiArray[i][@"image"]) {
            [self replaceCharactersInRange:range withAttributedString:emojiArray[i][@"image"]];
        } else {
            [self replaceCharactersInRange:range withString:emojiArray[i][@"text"]];
        }
    }
}

- (NSArray*)analyzeLink {
    NSMutableString * string = [[NSMutableString alloc] initWithString:self.string];
    
    NSRegularExpression *re = [[NSRegularExpression alloc] initWithPattern:LinkRegex
                                                                   options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators
                                                                     error:nil];
    NSMutableArray *resultsArray = [[re matchesInString:string
                                        options:NSMatchingReportCompletion
                                          range:NSMakeRange(0, string.length)] mutableCopy];
    
    NSMutableArray *linkRanges = [NSMutableArray arrayWithCapacity:resultsArray.count];
    
    for (NSTextCheckingResult *match in resultsArray) {
        NSRange range = [match range];
        
        NSString *href = [string substringWithRange:[match rangeAtIndex:1]];
        NSString *text = [string substringWithRange:[match rangeAtIndex:2]];
        
        [linkRanges addObject:@{KILabelLinkTypeKey:@(KILinkTypeURL),
                                KILabelLinkKey:text,
                                KILabelUrlKey:href,
                                KILabelRangeKey:[NSValue valueWithRange:range]}.mutableCopy];
    }
    
    for (int i=0; i<[linkRanges count]; i++) {
        NSRange range = [linkRanges[i][KILabelRangeKey] rangeValue];
        [self replaceCharactersInRange:range withString:linkRanges[i][KILabelLinkKey]];
        
        NSInteger fixLength = range.length - [linkRanges[i][KILabelLinkKey] length];
        range.length = [linkRanges[i][KILabelLinkKey] length];
        linkRanges[i][KILabelRangeKey] = [NSValue valueWithRange:range];
        
        //取出后面range,并更新
        for (int j=i+1; j<[linkRanges count]; j++) {
            NSRange fixRange = [linkRanges[j][KILabelRangeKey] rangeValue];
            fixRange.location -= fixLength;
            linkRanges[j][KILabelRangeKey] = [NSValue valueWithRange:fixRange];
        }
        

        
    }
    
    self.linkRanges = linkRanges;
//    
//    for (NSInteger i = linkArray.count -1; i >= 0; i--) {
//        NSRange range;
//        [linkArray[i][@"range"] getValue:&range];
//        [self addAttribute:NSLinkAttributeName value:[NSURL URLWithString:linkArray[i][@"href"]] range:range];
//        [self replaceCharactersInRange:range withString:linkArray[i][@"text"]];
//    }
    
    return nil;
}

@end
